#!/bin/bash

function upset_kv() {
    file="$1"
    k="$2"
    v="$3"
    if [ ! -f "$file" ]; then
        touch "$file"
    fi

    if grep -q "^$k " "$file"; then
        sed -i '' "s|^$k .*|$k $v|" "$file"
    else
        echo "$k $v" >>"$file"
    fi
}

# 获取数据的存储文件
function get_store_path() {
    # name="$1"
    # echo "${JAliasStorePath?:}/.jalias_${name:0:1}.data"
    res="${JAliasStorePath?:}/.jalias_kv.data"
    if [ ! -f "$res" ]; then
        touch "$res"
    fi
    echo "$res"
}

# 为当前目录添加一个别名
# @param1: alias name
function _jalias_add() {
    name=$(echo "$1" | tr '[:upper:]' '[:lower:]')
    cur_path=$(pwd)
    store_path=$(get_store_path)
    if upset_kv "$store_path" "$name" "$cur_path"; then
        printf "\033[32m%s\033[0m %s=%s\n" "● set success:" "$name" "$cur_path"
    else
        printf "\033[31m%s\033[0m %s=%s\n" "● set fail:" "$name" "$cur_path"
    fi
}

# 删除别名
# @param1: alias name
function _jalias_del() {
    name=$(echo "$1" | tr '[:upper:]' '[:lower:]')
    store_path=$(get_store_path)
    if sed -i '' "/^$name/d" "$store_path"; then
        printf "\033[32m%s\033[0m %s\n" "● del success:" "$name"
    else
        printf "\033[31m%s\033[0m %s\n" "● del success:" "$name"
    fi
}

function _jalias_clean() {
    store_path=$(get_store_path)
    echo "" > "$store_path"
    printf "\033[32m%s\033[0m\n" "● vlean success:"
}

# 列出所有的别名
function _jalias_list() {
    cat "$(get_store_path)"
}

# 列出所有的键，用于提示
function _jalias_keys() {
    store_path=$(get_store_path)
    awk '{print $1}' "$store_path" | sed "s|$|/|g" | tr '\n' ' '
}

function get_value() {
    pp="$(get_store_path)"
    grep -E "^$1 " "$pp" | awk '{print $2}'
}

# 替换路径中的别名
function _jalias_replace() {
    pre_path="$1"

    # root path or args
    special_chars='[~/\\-]'
    if [[ $pre_path =~ ^$special_chars ]]; then
        echo "$pre_path"
        return 0
    fi

    local PATH_ARRAY=()
    IFS='/' read "${read_arg:?}" PATH_ARRAY <<<"$pre_path"
    if [ ${#PATH_ARRAY[@]} -ge 1 ]; then
        first_key=${PATH_ARRAY[@]:0:1}
        value="$(get_value "$first_key")"
        if [[ -z "${value}" ]]; then
            echo "$pre_path"
            return 0
        fi

        new_list=("$value")
        new_list+=(${PATH_ARRAY[@]:1})

        local IFS='/'
        new_path="${new_list[*]}"
        echo "$new_path"
        return 0
    fi
    # echo "$pre_path"
}

function _jalias_exec() {
    local res=()
    for arg in "$@"; do
        local tmp=()
        IFS=" " read "${read_arg:?}" tmp <<<"$(_jalias_replace "$arg")"
        res+=("${tmp[@]}")
    done
    echo "${res[*]}"
}

# jalias cp -r proj/s proj/x
# get_value "proj"
# _jalias_exec "$@"